package netty.demo01;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

/**
 * HelloServer
 *
 * @author chenxin
 * @date 2022/05/25 22:00
 **/
public class HelloServer {

    public static void main(String[] args) {

        // 1. 创建一个启动器 负责组装netty组件
        new ServerBootstrap()
                // 2. BossEventLoop WorkerEventLoop(selector, thread) 事件组
                .group(new NioEventLoopGroup())
                // 3. 选择一个ServerSocketChannel实现 这里选择的是Nio的ServerSocketChannel
                .channel(NioServerSocketChannel.class)
                // 4. 决定了worker能执行哪些操作（handler）
                .childHandler(
                        // 5. channel代表服务器与客户端的通道 initializer 初始化
                        // 注意 这里是NioSocketChannel 上面的定义为NioServerSocketChannel
                        // 客户端那边传入也应该是NioSocketChannel
                        new ChannelInitializer<NioSocketChannel>() {
                            @Override
                            protected void initChannel(NioSocketChannel ch) throws Exception {
                                // 6. 添加具体的handler
                                ch.pipeline().addLast(new StringDecoder());
                                // 自定义handler
                                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                        // 读事件具体逻辑
                                        super.channelRead(ctx, msg);
                                        System.out.println(msg);
                                    }
                                });
                            }
                        })
                // 7. 绑定监听端口
                .bind(8080);


    }

}